<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="注意：只允许为第三级分类设置相关参数" :closable="false" show-icon type="warning">
      </el-alert>
      <el-row>
        <el-col>
          <span>选择商品分类:</span>
          <el-cascader v-model="Selectparams" :options="Paramslist" :props="paramsCascadar" @change="paramshandleChange">
          </el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="tabshandleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button size="mini" type="primary" :disabled="isdisable" @click="adddialogVisible = true">添加参数</el-button>
          <el-table row-key="id" border stripe :data="manydatalist">
            <el-table-column type="expand">
              <!-- 动态参数展开列 -->
              <template slot-scope="scope">
                <el-tag closable v-for="(item, index) in scope.row.attr_vals" :key="index"
                  @close="deleteTags(index, scope.row)">
                  {{ item }}
                </el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                  ref="saveTagInputRef" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="*"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="editDialog(scope.row)"></el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini"
                  @click="deleteDialog(scope.row.attr_id)"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button size="mini" type="primary" :disabled="isdisable" @click="adddialogVisible = true">添加参数</el-button>
          <el-table border stripe :data="onlydatalist">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag closable v-for="(item, index) in scope.row.attr_vals" :key="index"
                  @close="deleteTags(index, scope.row)">
                  {{ item }}
                </el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                  ref="saveTagInputRef" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="*"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="editDialog(scope.row)"></el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini"
                  @click="deleteDialog(scope.row.attr_id)"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog :title="'添加' + Textvalue" :visible.sync="adddialogVisible" width="50%" @close="addclose">
      <el-form :model="addForm" :rules="addFormrules" ref="addFormRef" label-width="100px">
        <el-form-item :label="Textvalue" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="adddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数对话框 -->
    <el-dialog :title="'修改' + Textvalue" :visible.sync="editialogVisible" width="50%">
      <el-form :model="editForm" :rules="editFormrules" ref="editFormRef" label-width="100px">
        <el-form-item label="参数名" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Params',
  data () {
    return {
      Paramslist: [],
      Selectparams: [],
      onlydatalist: [],
      manydatalist: [],
      addForm: {
        attr_name: ''
      },
      addFormrules: {
        attr_name: [
          {
            required: true, message: '请输入分类名称', trigger: 'blur'
          }
        ]
      },
      editForm: {
        attr_name: '',
        attr_id: ''
      },
      editFormrules: {
        attr_name:
          [{
            required: true, message: '请输入分类名称', trigger: 'blur'
          }]
      },
      paramsCascadar: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        expandTrigger: 'hover',
        checkStrictly: true
      },
      activeName: '',
      adddialogVisible: false,
      editialogVisible: false
    }
  },
  computed: {
    isdisable () {
      return this.Selectparams.length !== 3
    },
    cateId () {
      if (this.Selectparams.length === 3) {
        return this.Selectparams[this.Selectparams.length - 1]
      }
      return null
    },
    Textvalue () {
      if (this.activeName === 'many') {
        return '静态属性'
      } else return '动态参数'
    }
  },
  created () {
    this.getParamslist()
  },
  methods: {
    async getParamslist () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类列表数据失败')
      }
      this.Paramslist = res.data
    },
    async getParamsdata () {
      if (this.Selectparams.length !== 3) {
        this.Selectparams = []
        this.manydatalist = []
        this.onlydatalist = []
        return
      }
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: { sel: this.activeName }
      })
      if (res.meta.status !== 200) return this.$message.error('请求数据失败')
      if (this.activeName === 'only') {
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          item.inputVisible = false
          item.inputValue = ''
        })
        this.onlydatalist = res.data
      } else {
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
          item.inputVisible = false
          item.inputValue = ''
        })
        this.manydatalist = res.data
      }

      // console.log('静态:', this.onlydatalist)
      // console.log('动态:', this.manydatalist)
    },
    addclose () {
      this.$refs.addFormRef.resetFields()
    },
    paramshandleChange () {
      this.getParamsdata()
    },
    tabshandleClick () {
      this.getParamsdata()
    },
    addParams () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error('验证失败')
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) return this.$message.error('请求失败')
        this.$message.success('请求成功')
        this.adddialogVisible = false
        this.paramshandleChange()
      })
    },
    editDialog (edit) {
      this.editForm.attr_name = edit.attr_name
      this.editForm.attr_id = edit.attr_id
      this.editialogVisible = true
    },
    editParams () {
      this.$refs.editFormRef.validate(async valte => {
        if (!valte) return this.$message.error('表单验证失败')
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) {
          return this.$message.error('获取参数数据失败')
        }
        this.$message.success('修改' + this.Textvalue + '数据成功')
        this.paramshandleChange()
        this.editialogVisible = false
      })
    },
    async deleteDialog (attrid) {
      const removeDialog = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (removeDialog !== 'confirm') return this.$message.info('取消删除')
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${attrid}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除参数数据失败')
      }
      this.$message.success('删除' + this.Textvalue + '数据成功')
      this.getParamsdata()
    },
    // 对话款事件
    async handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputVisible = false
        row.inputValue = ''
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputVisible = false
      row.inputValue = ''
      this.saveAttrVals(row)
    },
    showInput (row) {
      row.inputVisible = true
      // $nextTick:在页面上元素被重新渲染之后，调用回调函数的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInputRef.$refs.input.focus()
      })
    },
    async saveAttrVals (row) {
      // 封装函数，完成保存可选项的操作
      // 发起请求，保存参数细项
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,
        { attr_name: row.attr_name, attr_sel: row.attr_sel, attr_vals: row.attr_vals.join(' ') })

      if (res.meta.status !== 200) {
        return this.$message.error('修改参数项失败')
      }
      this.$message.success('修改参数项成功')
    },
    deleteTags (index, row) {
      row.attr_vals.splice(index, 1)
      this.saveAttrVals(row)
    }
  }
}
</script>

<style lang="less" scoped>
.el-alert {
  margin: 10px 5px;
}

.el-cascader {
  width: 250px
}

.input-new-tag {
  width: 120px;
}

.el-tag {
  margin: 12px;
}
</style>
